import api from "@/api/api.js";
import toolAction from "@/tool/http/tool-action";
import { defineStore } from "pinia";

export const useLoginStore = defineStore("login", {
  state: () => {
    return {
      token: "",
      user: {},
      resources: undefined,
    };
  },
  getters: {
    loginRes(state) {
      if (!state.resources || state.resources.length < 1) {
        // state.refreshRes();
      }
      return state.resources || [];
    },
  },
  actions: {
    refreshRes() {
      toolAction
        .run("action-account-com-resource-allocation", this.user.id)
        .then((res) => (this.resources = res));
    },
    login(data) {
      api.login(data).then(async (res) => {
        this.token = res;
        this.user = await api.userinfo();
        this.refreshRes();
      });
    },
    async getUser() {
      if (!this.user) {
        this.user = await api.userinfo();
      }
      return this.user;
    },
    logout() {
      this.token = undefined;
      this.user = {};
      this.resources = undefined;
    },
  },
});
